import { Component, Input } from '@angular/core'
import { Widget } from '../../model'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare var echarts: any

let chart = null

@Component({
  selector: 'traffic-echarts-day',
  templateUrl: './traffic-echarts-day.html',
  styleUrls: ['./traffic-echarts-day.css']
})
// 流量统计（时）
export class TrafficEchartsDay implements Widget {
  @Input() componentData: any

  timeTypeFlow = '0'; //流量统计

  timeRangeFlow = 10; //流量查询时间段,默认十条数据

  loading = false
  chartOption = {
  };
  constructor(private jsonApiService: JsonApiService) { }
  ngOnInit() {

  }

  //流量统计类型
  timeTypeFlowChange(val) {
    this.timeTypeFlow = val;
    this.initChart();
  }

  //流量时间范围change回调
  timeRangeFlowChange() {
    if (!(this.timeRangeFlow > 0)) {
      this.jsonApiService.message('请输入大于0的数字查询')
      return
    }
    this.initChart();
  }

  initChart() {
    let barX: any[] = [],
      linkNumY: any[] = [],
      totalInBytesY: any[] = [],
      totalOutBytesY: any[] = [];
    const fillData = [{
      name: '链接数',
      type: 'line',
      data: linkNumY
    }, {
      name: '总进站',
      type: 'line',
      data: totalInBytesY
    }, {
      name: '总出站',
      type: 'line',
      data: totalOutBytesY
    }]
    const option = {
      title: {
        x: 'center',
        top: 6,
        textStyle: {
          fontSize: 14,
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function (params) {
          let res = '';
          const len = params.length;
          const dataIndex = params[0].dataIndex;
          for (let i = 0; i < len; i++) {
            for (let item in fillData) {
              if (params[i].seriesName == fillData[item].name) {
                if (params[i].seriesName !== '链接数') {
                  let val = fillData[item].data[dataIndex];
                  val = val + 'MB';
                  res = res + params[i].marker + params[i].seriesName + ':' + val + '</br>'
                } else {
                  const val = fillData[item].data[dataIndex];
                  res = res + params[i].name + '</br>' + params[i].marker + params[i].seriesName + ':' + val + '</br>'
                }
              }
            }
          }
          return res;
        }
      },
      grid: {
        top: '12',
        left: '22',
        right: '32',
        bottom: '22',
        containLabel: true
      },
      xAxis: [{
        type: 'category',
        data: barX,
        axisTick: {
          alignWithLabel: true
        }
      }],
      yAxis: [{
        type: 'value'
      }],
      series: fillData,
    };
    chart.clear();
    chart.setOption(option);
    this.loading = true
    let request = "state=" + Number(this.timeTypeFlow) + "&X=" + parseInt(this.timeRangeFlow + '');
    this.jsonApiService.http('control/station/traffic/hourDay/trafficStatisticsForHourDay.html', request, false).subscribe(data => {
      this.loading = false
      if (data.success) {
        if (!data.data) {
          this.jsonApiService.message('流量数据统计为空');
          return
        }
        const result = data.data;
        for (let item in result) {
          const temItem = item.split(' ');
          const lisItem = item.split(':');
          if (this.timeTypeFlow === '0') {
            barX.push(lisItem[0] + '时');
          } else if (this.timeTypeFlow === '1') {
            barX.push(temItem[0]);
          }
          result[item].totalInBytes = common.twoDecimal(result[item].totalInBytes / 1024 / 1024);
          result[item].totalOutBytes = common.twoDecimal(result[item].totalOutBytes / 1024 / 1024);
          linkNumY.push(result[item].linkNum);
          totalInBytesY.push(result[item].totalInBytes);
          totalOutBytesY.push(result[item].totalOutBytes);
        }
        chart.setOption({
          xAxis: [{
            data: barX
          }],
          series: fillData
        });
      }
    })
  }

  ngAfterViewInit() {
    setTimeout(() => {
      chart = echarts.init(document.getElementById('flow-day'));
      this.initChart()
      window.addEventListener('resize', this.resizeChart)
    }, 0)
  }

  ngOnDestroy() {
    if (!chart) return
    window.removeEventListener('resize', this.resizeChart)
    chart.dispose()
    chart = null
  }

  resizeChart() {
    chart && chart.resize()
  }

}
